package myTeam.timeShop.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import myTeam.timeShop.LikeService;
import myTeam.timeShop.bean.TbChar;
import myTeam.timeShop.bean.TbComment;
import myTeam.timeShop.bean.TbDemand;
import myTeam.timeShop.bean.TbLike;
import myTeam.timeShop.bean.TbRequest;
import myTeam.timeShop.bean.TbUser;
import myTeam.timeShop.entity.User;
import myTeam.timeShop.service.CarouselService;
import myTeam.timeShop.service.CharService;
import myTeam.timeShop.service.CommentService;
import myTeam.timeShop.service.DemandService;
import myTeam.timeShop.service.RequestService;
import myTeam.timeShop.service.SystemService;
import myTeam.timeShop.service.UserService;
import myTeam.timeShop.util.FileUpLoadUtil;
import myTeam.timeShop.util.MyMD5Util;
import myTeam.timeShop.util.MyMapBuilder;
import myTeam.timeShop.util.PageUtil;
import myTeam.timeShop.util.UserFaceUploadUtil;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

@Controller
@RequestMapping("/client/user")
@Api(description = "用户版块", value = "用户版块")
public class UserController {
	@Autowired
	LikeService likeService;
	@Autowired
	CommentService commentService;
	@Autowired
	CharService charService;
	@Autowired
	RequestService requestService;
	@Autowired
	DemandService demandService;
	@Autowired
	CarouselService carouselService;
	@Autowired
	UserService userService;
	@Autowired
	SystemService systemService;

	// @ResponseBody
	// @RequestMapping("/register")
	// public String test(String account,String password){
	// TbUser user = new TbUser();
	// user.setUserAccount(account);
	// user.setUserPassword(password);
	// UsernamePasswordToken token = new UsernamePasswordToken(account,
	// password);
	// try{
	// subject.login(token);
	// }catch (IncorrectCredentialsException e) {
	// // TODO: handle exception
	// return "帐号或密码错误";
	// }
	//
	// return subject.getPrincipal().toString();
	//
	// }
	// @RequiresAuthentication
	// @ResponseBody
	// @RequestMapping("/myBack")
	// public String myBack(){
	// System.out.println(SecurityUtils.getSubject(). isAuthenticated());
	// return "看到了";
	// }
	//
	//
	// /**
	// * 拦截没登录现象
	// * @return
	// */
	// @ExceptionHandler({UnauthorizedException.class})
	// @ResponseBody
	// public String processUnauthenticatedException() {
	//
	// return "对不起 用户还没登录";
	// }
	//
	// /**
	// * 拦截未登录异常
	// *
	// */
	// @ExceptionHandler({UnauthenticatedException.class})
	// @ResponseBody
	// public String sorry(){
	// return "对不起，请登录";
	// }

	/**
	 * 用户登录 jiangjintai 2016年3月25日
	 * 
	 * @param userAccount
	 * @param userPassword
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/login")
	@ApiOperation(value = "用户登录", httpMethod = "GET")
	public String login(
			@ApiParam(value = "用户账户", name = "userAccount", required = true) @RequestParam("userAccount") String userAccount,
			@ApiParam(value = "用户密码", name = "userPassword", required = true) @RequestParam("userPassword") String userPassword) {
		UsernamePasswordToken token = new UsernamePasswordToken(userAccount,
				userPassword);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return JSON
					.toJSONString(new MyMapBuilder(0, "对不起用户名或密码错误").build());
		}
		TbUser user = userService.doSomeThingForUserLogin(subject
				.getPrincipal().toString());
		return JSON.toJSONString(
				new MyMapBuilder(1, "登录成功").put("user", user)
						.put("carouselList", carouselService.findAll())
						.put("system", systemService.getNewSystem()).build(),
				SerializerFeature.DisableCircularReferenceDetect);
	}

	/**
	 * 修改用户信息 jiangjintai 2016年3月26日
	 * 
	 * @param userPassword
	 * @param userFace
	 * @param userName
	 * @param userSex
	 * @param userBirthday
	 *            生日格式为 yyyy-MM-dd
	 * @param userSchool
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateUser")
	@ApiOperation(value = "修改用户信息", httpMethod = "POST")
	public String updateUser(
			@ApiParam(value = "用户密码", name = "userPassword", required = false) @RequestParam("userPassword") String userPassword,
			@ApiParam(value = "用户头像", name = "userFace", required = false) @RequestParam("userFace") MultipartFile userFace,
			@ApiParam(value = "用户姓名", name = "userName", required = false) @RequestParam("userName") String userName,
			@ApiParam(value = "用户性别", name = "userSex", required = false) @RequestParam("userSex") String userSex,
			@ApiParam(value = "用户生日", name = "userBirthday", required = false) @RequestParam("userBirthday") String userBirthday,
			@ApiParam(value = "用户学校", name = "userSchool", required = false) @RequestParam("userSchool") String userSchool,
			@ApiParam(value = "用户od", name = "filterUserId", required = false) @RequestParam("filterUserId") String filterUserId,
			HttpServletRequest request,
			@ApiParam(value = "用户个性签名", name = "userSign", required = false) @RequestParam("userSign") String userSign) {
		TbUser user = userService.get(filterUserId);
		user.setUserPassword(userPassword!= null ? MyMD5Util
				.toMD5String(userPassword.trim()) : user.getUserPassword());
		user.setUserName(userName!= null ? userName.trim() : user
				.getUserName());
		user.setUserSign(userSign!= null ? userSign.trim() : user
				.getUserSign());
		user.setUserSex(userSex!= null ? userSex.trim() : user.getUserSex());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			user.setUserBirthday(sdf.parse(userBirthday));
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return JSON.toJSONString(new MyMapBuilder(0, "日期格式错误").build());
		}

		user.setUserSchool(userSchool != null ? userSchool.trim() : user
				.getUserSchool());
		String userFacePath = "";
		if (!userFace.isEmpty()) {
			UserFaceUploadUtil ufuu = new UserFaceUploadUtil();
			String status = ufuu.doUpload(userFace, request.getServletContext()
					.getRealPath("/"));
			switch (status) {
			case "-2":
				return JSON.toJSONString(new MyMapBuilder(0, "对不起，图片尺寸应小于15M")
						.build());

			case "-1":
				return JSON.toJSONString(new MyMapBuilder(0, "对不起，该文件不是图片")
						.build());

			case "0":
				return JSON.toJSONString(new MyMapBuilder(0, "出现未知错误").build());
			default:
				userFacePath = status;
				user.setUserFacePath(userFacePath);
			}
		} else {
			user.setUserFacePath(user.getUserFacePath());
		}

		userService.saveOrUpdate(user);// 修改后信息
		return JSON.toJSONString(new MyMapBuilder(1, "修改成功").put("user", user).build(),
				SerializerFeature.DisableCircularReferenceDetect);

	}

	/**
	 * 获取更新 jiangjintai 2016年3月26日
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getUpdate")
	@ApiOperation(value = "获取软件更新", httpMethod = "GET")
	public String getUpdate() {
		return JSON.toJSONString(new MyMapBuilder(1, "获取成功").put("system",
				systemService.getNewSystem()));
	}

	/**
	 * 获取我的需求 jiangjintai 2016年3月26日
	 * 
	 * @param pageNo
	 * @param size
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getMyDemand")
	@ApiOperation(value = "获取我的需求", httpMethod = "GET")
	public String getMyDemand(
			@ApiParam(value = "开始页面数0开始", name = "pageNo", required = true) @RequestParam("pageNo") String pageNo,
			@ApiParam(value = "跨域", name = "size", required = true) @RequestParam("size") String size,
			@ApiParam(value = "用户id", name = "filterUserId", required = true) @RequestParam("filterUserId") String filterUserId) {
		List<TbDemand> demandList = demandService.getUserDemand(pageNo, size,
				filterUserId);
		return JSON.toJSONString(
				new MyMapBuilder(1, "获取成功").put("demandList", demandList)
						.build(),
				SerializerFeature.DisableCircularReferenceDetect);
	}

	/**
	 * 修改我发布的需求状态 jiangjintai 2016年3月26日
	 * 
	 * @param demandStatus
	 * @param filterUserId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateMyDemand")
	@ApiOperation(value = "更新我的需求", httpMethod = "GET")
	public String updateMyDemand(
			@ApiParam(value = "更改我的需求状态2为完成，3为取消", name = "demandStatus", required = true) @RequestParam("demandStatus") String demandStatus,
			@ApiParam(value = "用户id", name = "filterUserId", required = true) @RequestParam("filterUserId") String filterUserId,
			@ApiParam(value = "需求id", name = "demandId", required = true) @RequestParam("demandId") String demandId) {
		TbDemand demand = demandService.get(demandId);
		if (demandStatus.endsWith("2")) {// 代表完成
			// 只有订单目前状态在进行中才能完成
			// 完成订单后两者经验都要增加

			if (demand.getDemandStatus().equals(1)) {
				demand.setDemandStatus(2);
				TbUser client = userService.get(demand
						.getTbUserByDemandClientId().getUserId() + "");
				TbUser user = userService.get(demand.getTbUserByDemandUserId()
						.getUserId() + "");

				client.setUserExperience(client.getUserExperience() + 5);
				user.setUserExperience(user.getUserExperience() + 2);

				demandService.saveOrUpdate(demand);
				userService.saveOrUpdate(user);
				userService.saveOrUpdate(client);

				return JSON.toJSONString(new MyMapBuilder(1, "恭喜您完成订单，经验+2")
						.build());

			} else {
				return JSON.toJSONString(new MyMapBuilder(0,
						"订单只有在进行中才能更新为完成状态").build());
			}

		} else {// 代表取消
				// 只有订单在进行中才能取消
			if (demand.getDemandStatus().equals(1)) {
				demand.setDemandStatus(0);
				demandService.saveOrUpdate(demand);
				return JSON.toJSONString(new MyMapBuilder(1, "取消成功").build());
			} else {
				return JSON.toJSONString(new MyMapBuilder(0,
						"订单只有在进行中才能更新为取消状态").build());
			}
		}
	}

	/**
	 * 查看我承接的时光单 jiangjintai 2016年3月27日
	 * 
	 * @param pageNo
	 * @param size
	 * @param filterUserId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getMyBussiness")
	@ApiOperation(value = "查看我承接的时光单", httpMethod = "GET")
	public String getMyBussiness(
			@ApiParam(value = "页面起始数", name = "pageNo", required = true) @RequestParam("pageNo") String pageNo,
			@ApiParam(value = "跨域", name = "size", required = true) @RequestParam("size") String size,
			@ApiParam(value = "用户id", name = "filterUserId", required = true) @RequestParam("filterUserId") String filterUserId) {
		List<TbDemand> demandList = demandService.getUserRequestDemand(pageNo,
				size, filterUserId);
		return JSON.toJSONString(
				new MyMapBuilder(1, "获取成功").put("demandList", demandList)
						.build(),
				SerializerFeature.DisableCircularReferenceDetect);
	}

	/**
	 * 修改我的请求状态 jiangjintai 2016年3月29日
	 * 
	 * @param requestId
	 * @param filterUserId
	 * @param type
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/updateMyRequest")
	@ApiOperation(value = "修改我的请求状态", httpMethod = "GET")
	public String updateMyRequest(
			@ApiParam(value = "请求id", name = "requestId", required = true) @RequestParam("requestId") String requestId,
			@ApiParam(value = "用户id", name = "filterUserId", required = true) @RequestParam("filterUserId") String filterUserId,
			@ApiParam(value = "1为允许，0为取消", name = "type", required = true) @RequestParam("type") String type) {
		requestService.updateMyRequest(requestId, type);
		return JSON.toJSONString(new MyMapBuilder(1, "修改成功").build());
	}

	/**
	 * 聊天，点赞，评论，需求请求监听接口 jiangjintai 2016年3月29日
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getMyAllMessage")
	@ApiOperation(value = "聊天，点赞，评论，需求请求监听接口", httpMethod = "GET")
	public String getMyAllMessage(
			@ApiParam(value = "用户id", name = "filterUserId", required = true) @RequestParam("filterUserId") String filterUserId) {
		List<TbChar> charList = charService.getAllMyNoSeeChar(filterUserId);
		List<TbComment> commentList = commentService
				.getAllMyNoSeeComment(filterUserId);
		List<TbLike> likeList = likeService.getAllMyNoSeeLike(filterUserId);
		List<TbRequest> requestList = requestService
				.getAllMyNoSeeRequest(filterUserId);
		return JSON.toJSONString(new MyMapBuilder(1, "获取成功")
				.put("charLike", charList).put("commentList", commentList)
				.put("likeList", likeList).put("requestList", requestList)
				.build());
	}
}
